<template>
  <div>
    <!-- 面包屑区域 开始 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑区域 结束 -->
    <!-- 卡片区域 开始 -->
    <el-card>
      <el-alert type="info" center show-icon :closable="false"
        >添加商品信息</el-alert
      >
      <!-- 进度条区域 开始 -->
      <el-steps :active="+activeName" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 进度条区域 结束 -->
      <!-- form表单区域 开始 -->
      <!-- label-position控制label标签独占一行 -->
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addFormRules"
        label-position="top"
      >
        <!-- 选项卡区域 开始 -->
        <el-tabs
          tab-position="left"
          v-model="activeName"
          :before-leave="tabBeforeLeaveHandle"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 表单---基本信息区域 开始 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="goodsCate"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                @change="cascaderHandleChange"
              ></el-cascader>
            </el-form-item>
            <!-- 表单---基本信息区域 结束 -->
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 表单---商品参数区域 开始 -->
            <el-form-item
              v-for="item in cateManydata"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 复选框区域 开始 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  :label="item1"
                  border
                ></el-checkbox>
              </el-checkbox-group>
              <!-- 复选框区域 结束 -->
            </el-form-item>
            <!-- 表单---商品参数区域 结束 -->
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in cateOnlydata"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://liufusong.top:8888/api/private/v1/upload"
              :on-success="handleUploadImgSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容区域 开始 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button @click="addGoods" type="primary">添加商品</el-button>
          </el-tab-pane>
          <!-- 商品内容区域 结束 -->
        </el-tabs>
        <!-- 选项卡区域 结束 -->
      </el-form>
      <!-- form表单区域 结束 -->
    </el-card>
    <!-- 卡片区域 结束 -->
    <!-- 图片预览 开始 -->
    <el-dialog
      :visible.sync="previewImgDialogVisible"
      width="50%"
    >
    <img :src="imgURL" alt="" style="width: 100%">
    </el-dialog>
    <!-- 图片预览 结束 -->
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 对话框
      previewImgDialogVisible: false,
      // 选项卡选中项的值
      activeName: '',
      // 添加商品表单数据
      addForm: {
        goods_name: '8449',
        goods_price: '12',
        goods_weight: '34',
        goods_number: '45',
        // 商品分类选择器选择的商品id
        goods_cat: [1, 3, 6],
        // 存储图片上传成功后后台返回的地址
        pics: [],
        goods_introduce: ''
      },
      // 添加商品表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类
      goodsCate: [],
      // 商品参数数据
      cateManydata: [],
      // 商品属性数据
      cateOnlydata: [],
      // 请求头
      headers: {
        Authorization: sessionStorage.getItem('token')
      },
      // 预览图片地址
      imgURL: ''
    }
  },

  created() {
    this.getGoodsCate()
  },

  methods: {
    async getGoodsCate() {
      const res = await this.$axios.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.goodsCate = res.data
    },
    // 级联选择器选择内容发生变化
    cascaderHandleChange() {
      const len = this.addForm.goods_cat.length
      if (len !== 3) {
        this.addForm.goods_cat = []
        return
      }
      console.log(this.addForm.goods_cat)
    },
    // 在离开基本信息标签页的时候对基本信息标签页进行判断
    // activeName点击前往的标签页, oldActiveName之前的标签页
    tabBeforeLeaveHandle(activeName, oldActiveName) {
      const len = this.addForm.goods_cat.length
      // 如果是在基本信息页面进行跳转并且级联选择器没有选择那么就阻止跳转
      if (oldActiveName === '0' && len !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 点击tab标签页触发的事件处理函数,
    // 当点击了商品参数要拿着级联中选择的商品分类的id向后台发送获取商品参数的请求
    async tabClick() {
      const cateId = this.addForm.goods_cat[2]
      if (this.activeName === '1') {
        const res = await this.$axios.get(
          '/categories/' + cateId + '/attributes',
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }
        // 处理res.data中每一项里面的attr_vals属性
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(' ')
        })
        this.cateManydata = res.data
      } else if (this.activeName === '2') {
        const res = await this.$axios.get(
          '/categories/' + cateId + '/attributes',
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }
        this.cateOnlydata = res.data
      }
    },
    // 图片预览
    handlePreview(file) {
      const tmpPath = file.response.data.tmp_path
      this.imgURL = 'http://liufusong.top:8888/' + tmpPath
      this.previewImgDialogVisible = true
    },
    // 删除图片
    handleRemove(file) {
      console.log(file)
      const tmpPath = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(item => {
        return item.pic === tmpPath
      })
      this.addForm.pics.splice(index, 1)
    },
    // 图片上传成功的回调
    handleUploadImgSuccess(res) {
      // console.log(res)
      this.addForm.pics.push({
        pic: res.data.tmp_path
      })
    },
    // 点击添加商品
    addGoods() {
      this.$refs.addForm.validate(async flag => {
        if (!flag) return this.$message.error('请填写表单必填项')
        const deepAddForm = _.cloneDeep(this.addForm)
        // console.log(deepAddForm === this.addForm)
        deepAddForm.goods_cat = deepAddForm.goods_cat.join(',')
        deepAddForm.attrs = []
        const attrData = [...this.cateManydata, ...this.cateOnlydata]
        console.log(attrData)
        attrData.forEach(item => {
          deepAddForm.attrs.push({
            attr_id: item.attr_id,
            attr_vals: Array.isArray(item.attr_vals) ? item.attr_vals.join(' ') : item.attr_vals
          })
        })
        const res = await this.$axios.post('/goods', deepAddForm)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang='less'>
/deep/.el-step__title {
  font-size: 13px;
}
/deep/.el-alert__icon.is-big {
  font-size: 18px;
}
.el-checkbox {
  margin: 0;
}
.quill-editor {
  /deep/ .ql-editor {
    height: 300px;
  }
}
.el-button {
  margin-top: 10px;
}
</style>
